from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.db.database import get_db
from app.db.models import User, Resume
from app.schemas import (
    Resume as ResumeSchema,
    ResumeCreate,
    ResumeUpdate,
    PersonalInfo,
    PersonalInfoCreate,
    PersonalInfoUpdate,
    Education,
    EducationCreate,
    EducationUpdate,
    WorkExperience,
    WorkExperienceCreate,
    WorkExperienceUpdate,
    Skill,
    SkillCreate,
    SkillUpdate,
    Certificate,
    CertificateCreate,
    CertificateUpdate,
    ResumeGenerateRequest
)
from app.crud import (
    get_resume,
    get_resumes_by_user,
    create_resume,
    update_resume,
    delete_resume,
    get_personal_info,
    create_personal_info,
    update_personal_info,
    delete_personal_info,
    get_educations_by_resume,
    create_education,
    update_education,
    delete_education,
    get_work_experiences_by_resume,
    create_work_experience,
    update_work_experience,
    delete_work_experience,
    get_skills_by_resume,
    create_skill,
    update_skill,
    delete_skill,
    get_certificates_by_resume,
    create_certificate,
    update_certificate,
    delete_certificate
)
from app.core.security import get_current_active_user
from app.services.resume_generator import generate_resume_pdf, generate_resume_docx
from fastapi.responses import FileResponse

# 创建简历路由器
router = APIRouter()

# 获取用户的所有简历
@router.get("/", response_model=List[ResumeSchema])
def read_resumes(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    resumes = get_resumes_by_user(db, user_id=current_user.id, skip=skip, limit=limit)
    return resumes

# 获取单个简历详情
@router.get("/{resume_id}", response_model=ResumeSchema)
def read_resume(
    resume_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    return db_resume

# 创建新简历
@router.post("/", response_model=ResumeSchema, status_code=status.HTTP_201_CREATED)
def create_user_resume(
    resume: ResumeCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    return create_resume(db=db, resume=resume, user_id=current_user.id)

# 更新简历
@router.put("/{resume_id}", response_model=ResumeSchema)
def update_user_resume(
    resume_id: int,
    resume: ResumeUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    return update_resume(db=db, db_resume=db_resume, resume=resume)

# 删除简历
@router.delete("/{resume_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_user_resume(
    resume_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    delete_resume(db=db, resume_id=resume_id)
    return None

# 个人信息相关端点
@router.get("/{resume_id}/personal-info", response_model=PersonalInfo)
def read_personal_info(
    resume_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    db_personal_info = get_personal_info(db, resume_id=resume_id)
    if db_personal_info is None:
        raise HTTPException(status_code=404, detail="Personal info not found")
    return db_personal_info

@router.post("/{resume_id}/personal-info", response_model=PersonalInfo, status_code=status.HTTP_201_CREATED)
def create_personal_info_for_resume(
    resume_id: int,
    personal_info: PersonalInfoCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    return create_personal_info(db=db, personal_info=personal_info, resume_id=resume_id)

@router.put("/{resume_id}/personal-info", response_model=PersonalInfo)
def update_personal_info_for_resume(
    resume_id: int,
    personal_info: PersonalInfoUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    db_personal_info = get_personal_info(db, resume_id=resume_id)
    if db_personal_info is None:
        raise HTTPException(status_code=404, detail="Personal info not found")
    return update_personal_info(db=db, db_personal_info=db_personal_info, personal_info=personal_info)

@router.delete("/{resume_id}/personal-info", status_code=status.HTTP_204_NO_CONTENT)
def delete_personal_info_for_resume(
    resume_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    db_personal_info = get_personal_info(db, resume_id=resume_id)
    if db_personal_info is None:
        raise HTTPException(status_code=404, detail="Personal info not found")
    delete_personal_info(db=db, personal_info_id=db_personal_info.id)
    return None

# 教育经历相关端点
@router.get("/{resume_id}/education", response_model=List[Education])
def read_educations(
    resume_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    return get_educations_by_resume(db, resume_id=resume_id)

@router.post("/{resume_id}/education", response_model=Education, status_code=status.HTTP_201_CREATED)
def create_education_for_resume(
    resume_id: int,
    education: EducationCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    return create_education(db=db, education=education, resume_id=resume_id)

@router.put("/{resume_id}/education/{education_id}", response_model=Education)
def update_education_for_resume(
    resume_id: int,
    education_id: int,
    education: EducationUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    db_education = get_education(db, education_id=education_id)
    if db_education is None:
        raise HTTPException(status_code=404, detail="Education not found")
    if db_education.resume_id != resume_id:
        raise HTTPException(status_code=400, detail="Education does not belong to this resume")
    return update_education(db=db, db_education=db_education, education=education)

@router.delete("/{resume_id}/education/{education_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_education_for_resume(
    resume_id: int,
    education_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    db_education = get_education(db, education_id=education_id)
    if db_education is None:
        raise HTTPException(status_code=404, detail="Education not found")
    if db_education.resume_id != resume_id:
        raise HTTPException(status_code=400, detail="Education does not belong to this resume")
    delete_education(db=db, education_id=education_id)
    return None

# 工作经历相关端点
@router.get("/{resume_id}/work-experience", response_model=List[WorkExperience])
def read_work_experiences(
    resume_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    return get_work_experiences_by_resume(db, resume_id=resume_id)

@router.post("/{resume_id}/work-experience", response_model=WorkExperience, status_code=status.HTTP_201_CREATED)
def create_work_experience_for_resume(
    resume_id: int,
    work_experience: WorkExperienceCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    return create_work_experience(db=db, work_experience=work_experience, resume_id=resume_id)

@router.put("/{resume_id}/work-experience/{work_experience_id}", response_model=WorkExperience)
def update_work_experience_for_resume(
    resume_id: int,
    work_experience_id: int,
    work_experience: WorkExperienceUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    db_work_experience = get_work_experience(db, work_experience_id=work_experience_id)
    if db_work_experience is None:
        raise HTTPException(status_code=404, detail="Work experience not found")
    if db_work_experience.resume_id != resume_id:
        raise HTTPException(status_code=400, detail="Work experience does not belong to this resume")
    return update_work_experience(db=db, db_work_experience=db_work_experience, work_experience=work_experience)

@router.delete("/{resume_id}/work-experience/{work_experience_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_work_experience_for_resume(
    resume_id: int,
    work_experience_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    db_work_experience = get_work_experience(db, work_experience_id=work_experience_id)
    if db_work_experience is None:
        raise HTTPException(status_code=404, detail="Work experience not found")
    if db_work_experience.resume_id != resume_id:
        raise HTTPException(status_code=400, detail="Work experience does not belong to this resume")
    delete_work_experience(db=db, work_experience_id=work_experience_id)
    return None

# 技能相关端点
@router.get("/{resume_id}/skills", response_model=List[Skill])
def read_skills(
    resume_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    return get_skills_by_resume(db, resume_id=resume_id)

@router.post("/{resume_id}/skills", response_model=Skill, status_code=status.HTTP_201_CREATED)
def create_skill_for_resume(
    resume_id: int,
    skill: SkillCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    return create_skill(db=db, skill=skill, resume_id=resume_id)

@router.put("/{resume_id}/skills/{skill_id}", response_model=Skill)
def update_skill_for_resume(
    resume_id: int,
    skill_id: int,
    skill: SkillUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    db_skill = get_skill(db, skill_id=skill_id)
    if db_skill is None:
        raise HTTPException(status_code=404, detail="Skill not found")
    if db_skill.resume_id != resume_id:
        raise HTTPException(status_code=400, detail="Skill does not belong to this resume")
    return update_skill(db=db, db_skill=db_skill, skill=skill)

@router.delete("/{resume_id}/skills/{skill_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_skill_for_resume(
    resume_id: int,
    skill_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    db_skill = get_skill(db, skill_id=skill_id)
    if db_skill is None:
        raise HTTPException(status_code=404, detail="Skill not found")
    if db_skill.resume_id != resume_id:
        raise HTTPException(status_code=400, detail="Skill does not belong to this resume")
    delete_skill(db=db, skill_id=skill_id)
    return None

# 证书相关端点
@router.get("/{resume_id}/certificates", response_model=List[Certificate])
def read_certificates(
    resume_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    return get_certificates_by_resume(db, resume_id=resume_id)

@router.post("/{resume_id}/certificates", response_model=Certificate, status_code=status.HTTP_201_CREATED)
def create_certificate_for_resume(
    resume_id: int,
    certificate: CertificateCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    return create_certificate(db=db, certificate=certificate, resume_id=resume_id)

@router.put("/{resume_id}/certificates/{certificate_id}", response_model=Certificate)
def update_certificate_for_resume(
    resume_id: int,
    certificate_id: int,
    certificate: CertificateUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    db_certificate = get_certificate(db, certificate_id=certificate_id)
    if db_certificate is None:
        raise HTTPException(status_code=404, detail="Certificate not found")
    if db_certificate.resume_id != resume_id:
        raise HTTPException(status_code=400, detail="Certificate does not belong to this resume")
    return update_certificate(db=db, db_certificate=db_certificate, certificate=certificate)

@router.delete("/{resume_id}/certificates/{certificate_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_certificate_for_resume(
    resume_id: int,
    certificate_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    db_certificate = get_certificate(db, certificate_id=certificate_id)
    if db_certificate is None:
        raise HTTPException(status_code=404, detail="Certificate not found")
    if db_certificate.resume_id != resume_id:
        raise HTTPException(status_code=400, detail="Certificate does not belong to this resume")
    delete_certificate(db=db, certificate_id=certificate_id)
    return None

# 生成简历文件
@router.post("/generate")
def generate_resume(
    request: ResumeGenerateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    db_resume = get_resume(db, resume_id=request.resume_id)
    if db_resume is None:
        raise HTTPException(status_code=404, detail="Resume not found")
    if db_resume.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    
    # 根据格式生成不同的文件
    if request.format == "pdf":
        file_path = generate_resume_pdf(db_resume, db, template_type=request.template_type)
    elif request.format == "docx":
        file_path = generate_resume_docx(db_resume, db, template_type=request.template_type)
    else:
        raise HTTPException(status_code=400, detail="Unsupported format")
    
    if not file_path:
        raise HTTPException(status_code=500, detail="Failed to generate resume")
    
    # 返回文件下载响应
    return FileResponse(path=file_path, filename=f"resume_{db_resume.id}.{request.format}")